package com.ruoyi.web.controller.energy;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.energy.service.IEmsDeviceDataStatisticsService;

/**
 * 图表数据Controller
 * 
 * @author ruoyi
 * @date 2025-01-04
 */
@RestController
@RequestMapping("/energy/charts")
public class EmsChartsController extends BaseController {
    
    @Autowired
    private IEmsDeviceDataStatisticsService statisticsService;

    /**
     * 获取趋势图数据
     */
    @PreAuthorize("@ss.hasPermi('energy:monitor:list')")
    @GetMapping("/trend")
    public AjaxResult getTrendData(@RequestParam(required = false) String deviceId,
                                  @RequestParam(required = false) String deviceCode,
                                  @RequestParam(required = false) String startTime,
                                  @RequestParam(required = false) String endTime,
                                  @RequestParam(defaultValue = "1h") String interval) {
        try {
            Date start, end;

            // 如果没有提供时间范围，使用默认的最近24小时
            if (startTime == null || endTime == null) {
                end = new Date();
                start = new Date(end.getTime() - 24 * 60 * 60 * 1000L);
            } else {
                start = DateUtils.parseDate(startTime);
                end = DateUtils.parseDate(endTime);

                if (start == null || end == null) {
                    return AjaxResult.error("时间参数格式错误");
                }
            }

            // 如果提供了deviceId但没有deviceCode，需要通过deviceId查询deviceCode
            // 这里暂时使用deviceCode，后续可以完善
            String targetDeviceCode = deviceCode;

            if (targetDeviceCode != null && !targetDeviceCode.isEmpty()) {
                List<Map<String, Object>> data = statisticsService.getDeviceEnergyStatistics(
                    targetDeviceCode, null, start, end, getGroupByFromInterval(interval));
                return AjaxResult.success(formatTrendData(data));
            } else {
                // 如果没有指定设备，返回所有设备的汇总数据
                List<Map<String, Object>> data = statisticsService.getDeviceEnergyStatistics(
                    null, null, start, end, getGroupByFromInterval(interval));
                return AjaxResult.success(formatTrendData(data));
            }
        } catch (Exception e) {
            return AjaxResult.error("获取趋势图数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取能耗分布数据
     */
    @PreAuthorize("@ss.hasPermi('energy:monitor:list')")
    @GetMapping("/distribution")
    public AjaxResult getDistributionData(@RequestParam(required = false) String startTime,
                                         @RequestParam(required = false) String endTime,
                                         @RequestParam(required = false) String energyType) {
        try {
            Date start, end;

            // 如果没有提供时间范围，使用默认的最近24小时
            if (startTime == null || endTime == null) {
                end = new Date();
                start = new Date(end.getTime() - 24 * 60 * 60 * 1000L);
            } else {
                start = DateUtils.parseDate(startTime);
                end = DateUtils.parseDate(endTime);

                if (start == null || end == null) {
                    return AjaxResult.error("时间参数格式错误");
                }
            }

            // 获取不同能源类型的能耗分布数据
            List<Map<String, Object>> result = new java.util.ArrayList<>();

            // 如果指定了能源类型，只查询该类型
            if (energyType != null && !energyType.isEmpty()) {
                List<Map<String, Object>> data = statisticsService.getDeviceEnergyRanking(
                    energyType, start, end, 10);
                result.addAll(formatDistributionData(data, energyType));
            } else {
                // 查询所有能源类型的分布 - 使用数字编码和英文名称都尝试
                String[] energyTypes = {"1", "2", "3", "4", "ELECTRIC", "GAS", "WATER", "STEAM"};
                for (String type : energyTypes) {
                    List<Map<String, Object>> data = statisticsService.getDeviceEnergyRanking(
                        type, start, end, 5);
                    if (data != null && !data.isEmpty()) {
                        result.addAll(formatDistributionData(data, type));
                    }
                }

                // 如果仍然没有数据，尝试获取设备级别的能耗分布
                if (result.isEmpty()) {
                    List<Map<String, Object>> deviceData = statisticsService.getDeviceEnergyStatistics(
                        null, null, start, end, "device");
                    result.addAll(formatDeviceDistributionData(deviceData));
                }
            }

            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("获取能耗分布数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取设备效率分析数据
     */
    @PreAuthorize("@ss.hasPermi('energy:monitor:list')")
    @GetMapping("/efficiency/{deviceCode}")
    public AjaxResult getEfficiencyData(@PathVariable("deviceCode") String deviceCode,
                                       @RequestParam String startTime,
                                       @RequestParam String endTime) {
        try {
            Date start = DateUtils.parseDate(startTime);
            Date end = DateUtils.parseDate(endTime);
            
            Map<String, Object> data = statisticsService.getDeviceEfficiencyAnalysis(deviceCode, start, end);
            return AjaxResult.success(formatEfficiencyData(data));
        } catch (Exception e) {
            return AjaxResult.error("获取设备效率分析数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取负载分析数据
     */
    @PreAuthorize("@ss.hasPermi('energy:monitor:list')")
    @GetMapping("/load/{deviceCode}")
    public AjaxResult getLoadData(@PathVariable("deviceCode") String deviceCode,
                                 @RequestParam(required = false) String startTime,
                                 @RequestParam(required = false) String endTime,
                                 @RequestParam(defaultValue = "1h") String interval) {
        try {
            Date start, end;

            // 如果没有提供时间范围，使用默认的最近24小时
            if (startTime == null || endTime == null) {
                end = new Date();
                start = new Date(end.getTime() - 24 * 60 * 60 * 1000L);
            } else {
                start = DateUtils.parseDate(startTime);
                end = DateUtils.parseDate(endTime);

                if (start == null || end == null) {
                    return AjaxResult.error("时间参数格式错误");
                }
            }

            List<Map<String, Object>> data = statisticsService.getDeviceLoadTrend(
                deviceCode, start, end, interval);

            return AjaxResult.success(formatLoadData(data));
        } catch (Exception e) {
            return AjaxResult.error("获取负载分析数据失败: " + e.getMessage());
        }
    }

    // ==================== 私有方法 ====================

    /**
     * 将时间间隔转换为groupBy参数
     */
    private String getGroupByFromInterval(String interval) {
        switch (interval.toLowerCase()) {
            case "5m":
            case "15m":
            case "30m":
            case "1h":
                return "hour";
            case "1d":
                return "day";
            case "1w":
            case "1m":
                return "month";
            default:
                return "hour";
        }
    }

    /**
     * 格式化趋势数据
     */
    private List<Map<String, Object>> formatTrendData(List<Map<String, Object>> data) {
        // 将数据格式化为前端期望的格式
        for (Map<String, Object> item : data) {
            // 确保时间字段名为 ts
            if (item.containsKey("_wstart")) {
                item.put("ts", item.get("_wstart"));
                item.remove("_wstart");
            }
            if (item.containsKey("time_point")) {
                item.put("ts", item.get("time_point"));
                item.remove("time_point");
            }
        }
        return data;
    }

    /**
     * 格式化能耗分布数据
     */
    private List<Map<String, Object>> formatDistributionData(List<Map<String, Object>> data, String energyType) {
        List<Map<String, Object>> result = new java.util.ArrayList<>();

        // 计算总能耗
        double totalConsumption = data.stream()
            .mapToDouble(item -> {
                Object consumption = item.get("total_consumption");
                return consumption != null ? ((Number) consumption).doubleValue() : 0.0;
            })
            .sum();

        // 将数据格式化为前端期望的格式
        for (Map<String, Object> item : data) {
            Map<String, Object> formattedItem = new HashMap<>();

            // 设置能源类型名称
            String typeName = getEnergyTypeName(energyType);
            formattedItem.put("energyType", energyType);
            formattedItem.put("name", typeName);

            // 设置能耗值
            Object consumption = item.get("total_consumption");
            double value = consumption != null ? ((Number) consumption).doubleValue() : 0.0;
            formattedItem.put("totalEnergy", value);
            formattedItem.put("value", value);

            // 计算百分比
            double percentage = totalConsumption > 0 ? (value / totalConsumption) * 100 : 0;
            formattedItem.put("percentage", Math.round(percentage * 100.0) / 100.0);

            result.add(formattedItem);
        }

        return result;
    }

    /**
     * 格式化设备级别的能耗分布数据
     */
    private List<Map<String, Object>> formatDeviceDistributionData(List<Map<String, Object>> data) {
        List<Map<String, Object>> result = new java.util.ArrayList<>();

        if (data == null || data.isEmpty()) {
            return result;
        }

        // 计算总能耗
        double totalConsumption = data.stream()
            .mapToDouble(item -> {
                Object consumption = item.get("total_energy");
                if (consumption == null) {
                    consumption = item.get("avg_power");
                }
                return consumption != null ? ((Number) consumption).doubleValue() : 0.0;
            })
            .sum();

        // 将数据格式化为前端期望的格式
        for (Map<String, Object> item : data) {
            Map<String, Object> formattedItem = new HashMap<>();

            // 设置设备名称
            String deviceCode = (String) item.get("device_code");
            formattedItem.put("name", deviceCode != null ? deviceCode : "未知设备");
            formattedItem.put("deviceName", deviceCode);

            // 设置能耗值
            Object consumption = item.get("total_energy");
            if (consumption == null) {
                consumption = item.get("avg_power");
            }
            double value = consumption != null ? ((Number) consumption).doubleValue() : 0.0;
            formattedItem.put("totalEnergy", value);
            formattedItem.put("value", value);

            // 计算百分比
            double percentage = totalConsumption > 0 ? (value / totalConsumption) * 100 : 0;
            formattedItem.put("percentage", Math.round(percentage * 100.0) / 100.0);

            if (value > 0) {
                result.add(formattedItem);
            }
        }

        return result;
    }

    /**
     * 获取能源类型名称
     */
    private String getEnergyTypeName(String energyType) {
        switch (energyType) {
            case "1":
            case "electric":
                return "电力";
            case "2":
            case "gas":
                return "燃气";
            case "3":
            case "water":
                return "水";
            case "4":
            case "steam":
                return "蒸汽";
            default:
                return "未知";
        }
    }

    /**
     * 格式化效率数据
     */
    private List<Map<String, Object>> formatEfficiencyData(Map<String, Object> data) {
        List<Map<String, Object>> result = new java.util.ArrayList<>();
        // 这里需要根据实际的效率数据结构进行格式化
        // 暂时返回空数据
        return result;
    }

    /**
     * 格式化负载数据
     */
    private List<Map<String, Object>> formatLoadData(List<Map<String, Object>> data) {
        // 将数据格式化为前端期望的格式
        for (Map<String, Object> item : data) {
            if (item.containsKey("load_rate")) {
                item.put("loadRate", item.get("load_rate"));
                item.remove("load_rate");
            }
            if (item.containsKey("time_point")) {
                item.put("time", item.get("time_point"));
                item.remove("time_point");
            }
        }
        return data;
    }
}
